﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using HtmlAgilityPack;
using System.Text.RegularExpressions;
using WebProxyApplication.Blocked;

namespace WebProxyApplication.FormCheck
{
    public class HtmlChecker
    {
        private static Regex protocolPrefix = new Regex(@"^(http|https)");

        public static bool IsHtmlSafe(string html, out BlockedReason blockedReason)
        {
            HtmlDocument htmlDoc;
            HtmlNodeCollection nodes;
            HtmlAttribute att;
            bool isSafe = false;
            bool isExternalForm; // the form GETs or POSTs data to an outside website
            string formAction;
            
            blockedReason = BlockedReason.Unknown;

            try
            {
                htmlDoc = new HtmlDocument();
                htmlDoc.LoadHtml(html);

                nodes = htmlDoc.DocumentNode.SelectNodes("//form");
                if (nodes != null)
                {
                    foreach (HtmlNode form in nodes)
                    {
                        att = form.Attributes["action"];
                        if (att != null)
                        {
                            formAction = att.Value;
                            ProxyLogger.Log.DebugFormat("Form found with action {0}", formAction);

                            // check to see if the form links to an external site -- assuming it is an external site if it starts with http or https
                            if (protocolPrefix.IsMatch(formAction))
                            {
                                isExternalForm = true;
                            }
                            else
                            {
                                isExternalForm = false;
                            }

                            if (isExternalForm)
                            {
                                if (Utils.isPhishUrl(formAction))
                                {
                                    blockedReason = BlockedReason.PhishingSite;
                                    ProxyLogger.Log.WarnFormat("form found with action to known phishing site (action={0})", formAction);
                                    return false;
                                }
                            }
                        }
                    }
                }
                isSafe = true;
            }
            catch (Exception ex)
            {
                blockedReason = BlockedReason.Unknown;
                ProxyLogger.Log.Error("Could not check html due to an error:", ex);
                isSafe = false;
            }
            return isSafe;
        }
    }
}